Page({
  data: {
    userId: null,
    userInfo: {},
    activeTab: 'recipes',
    recipeList: [],
    workList: [],
    isFollowed: false,
    loading: true,
    operating: false, // 用于控制关注按钮加载状态
    followCount: 0, // 关注数量
    fanCount: 0,    // 粉丝数量
    likesCount: 0   // 收到的赞数量
  },

  onLoad(options) {
    const { userId } = options;
    console.log('onLoad获取到的userId：', userId);
    
    // 校验userId有效性
    if (!userId) {
      wx.showToast({ title: '用户ID无效，无法加载', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }

    this.setData({ userId });
    this.checkTokenAndLoadData();
    this.loadWorkData(); // 加载作品数据
  },

  // 检查token并加载基础数据
  checkTokenAndLoadData() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }
    // 加载用户详情和菜谱数据
    this.loadUserDetail();
    this.loadUserContent();
  },

  // 加载用户详情
  loadUserDetail() {
    const { userId } = this.data;
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/userr/users/withRecipes/${userId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('用户详情接口响应：', res.data);

        // 处理token失效
        if (res.data.code === 401 || res.data.code === 403) {
          wx.removeStorageSync('token');
          wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
          setTimeout(() => wx.navigateTo({ url: '/pages/login/login' }), 1500);
          return;
        }

        if (res.data?.code === 200 && res.data.data) {
          const rawUserInfo = res.data.data;
          const userInfo = {
            id: rawUserInfo.id,
            name: rawUserInfo.nickname || '未知用户',
            avatar: rawUserInfo.avatarUrl ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${rawUserInfo.avatarUrl}` : '/images/default-avatar.png',
            gender: rawUserInfo.sex === 0 ? '男' : rawUserInfo.sex === 1 ? '女' : '未知',
            joinYear: rawUserInfo.joinTime ? rawUserInfo.joinTime.split('-')[0] : '',
            points: rawUserInfo.totalPoint || 0,
            following: rawUserInfo.followingCount || 0,
            followers: rawUserInfo.followerCount || 0,
            likesReceived: rawUserInfo.likesCount|| 0 ,
            // 直接使用接口返回的菜谱列表长度（不依赖过滤后的数据）
            recipeCount: rawUserInfo.recipesList?.length || 0,
            workCount: rawUserInfo.worksList?.length || 0,
            isVip: rawUserInfo.isVip === 1,
            vipExpireDate: rawUserInfo.vipExpireTime ? rawUserInfo.vipExpireTime.replace(/-/g, '/') : '',
            description: rawUserInfo.introduce || '暂无简介',
            isFollowed: this.data.isFollowed
          };
          this.setData({
            userInfo,
            loading: false
          });

          // 用户详情加载成功后，加载关注、粉丝、赞数量
          this.loadFollowCount();
          this.loadFanCount();
          this.loadLikesCount();
        } else {
          wx.showToast({ title: '用户信息加载失败', icon: 'none' });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('用户详情请求失败：', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
        this.setData({ loading: false });
      }
    });
  },

  // 加载菜谱数据
  loadUserContent() {
    const { userId } = this.data;
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/userr/users/withRecipes/${userId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('菜谱接口响应：', res.data);

        // 先判断接口是否成功
        if (res.data?.code !== 200) {
          wx.showToast({ title: `接口错误：${res.data.msg || '未知错误'}`, icon: 'none' });
          return;
        }

        // 判断recipesList是否存在且为数组
        const rawRecipes = res.data.data?.recipesList;
        if (!Array.isArray(rawRecipes)) {
          console.error('接口返回的recipesList不是数组：', rawRecipes);
          wx.showToast({ title: '菜谱数据格式错误', icon: 'none' });
          this.setData({ recipeList: [] });
          return;
        }

        // 格式化菜谱数据
        const recipeList = rawRecipes.map(recipe => ({
          id: recipe.id || '',
          title: recipe.title || '未命名菜谱',
          // 确保图片路径完整
          imageUrl: recipe.coverUrl ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${recipe.coverUrl}` : '/images/default-recipe.png',
          isVideo: recipe.mediaType === 2,
          likes: recipe.collectCount || 0,
          status: recipe.status || 0 // 记录原始状态，方便调试
        })).filter(recipe => recipe.id); // 仅过滤无ID的无效数据

        // 直接更新数据
        this.setData({
          recipeList: recipeList
        }, () => {
          console.log('菜谱数据加载完成（共', recipeList.length, '条）：', this.data.recipeList);
          // 若数据为空，显示提示
          if (recipeList.length === 0) {
            wx.showToast({ title: '未获取到菜谱数据', icon: 'none' });
          }
        });
      },
      fail: (err) => {
        console.error('菜谱请求失败：', err);
        wx.showToast({ title: '菜谱加载失败', icon: 'none' });
        this.setData({ recipeList: [] });
      }
    });
  },

  // 加载作品数据
  loadWorkData() {
    const { userId } = this.data;
    const token = wx.getStorageSync('token');
    const that = this;

    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      that.setData({ workList: [], 'userInfo.workCount': 0 });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/users/withWorks/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success(res) {
        console.log('作品接口响应：', res.data);
        if (res.data?.code === 200 && res.data.data) {
          const workData = res.data.data;
          const originWorks = Array.isArray(workData.worksList) ? workData.worksList : [];
          
          const workList = originWorks.map(work => ({
            id: work.id || work.workId,
            title: work.title || '未命名作品',
            imageUrl: work.coverUrl || work.coverImg 
              ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${work.coverUrl || work.coverImg}` 
              : '/images/default-work.png',
            isVideo: work.mediaType === 2,
            likes: work.collectCount || work.likesCount || 0
          }));

          that.setData({
            workList,
            'userInfo.workCount': workList.length
          }, () => {
            console.log('作品数据加载完成：', that.data.workList);
          });
        } else {
          wx.showToast({ title: '作品数据获取失败', icon: 'none' });
          that.setData({ workList: [], 'userInfo.workCount': 0 });
        }
      },
      fail(err) {
        console.error('作品请求失败：', err);
        that.setData({ workList: [], 'userInfo.workCount': 0 });
        wx.showToast({ title: '作品加载失败', icon: 'none' });
      }
    });
  },

  // 标签切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
    // 切换到作品标签时重新加载数据
    if (tab === 'works' && this.data.workList.length === 0) {
      this.loadWorkData();
    }
  },

  // 关注/取消关注
  onFollowTap() {
    if (this.data.operating) return;
    this.setData({ operating: true });

    const isFollowed = !this.data.isFollowed;
    const userInfo = { ...this.data.userInfo };
    userInfo.followers += isFollowed ? 1 : -1;

    // 模拟接口延迟
    setTimeout(() => {
      this.setData({
        isFollowed,
        userInfo,
        operating: false
      });
      wx.showToast({
        title: isFollowed ? '关注成功' : '已取消关注',
        icon: 'success'
      });
      // 关注状态变化后重新加载粉丝数
      this.loadFanCount();
    }, 800);
  },

  // 加载关注数量（已修复）
  loadFollowCount() {
    const { userId } = this.data; // 获取被查看用户的ID
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/follow/count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('关注数量接口返回:', res.data);
        if (res.data.code === 200) {
          const followCount = res.data.data || 0;
          this.setData({
            followCount: followCount,
            'userInfo.following': followCount
          });
        } else {
          wx.showToast({ title: '获取关注数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('关注数量请求失败:', err);
        wx.showToast({ title: '关注数量加载失败', icon: 'none' });
      }
    });
  },

  // 加载粉丝数量（已修复）
  loadFanCount() {
    const { userId } = this.data; // 获取被查看用户的ID
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/follow/fan-count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('粉丝数量接口返回:', res.data);
        if (res.data.code === 200) {
          const fanCount = res.data.data || 0;
          this.setData({
            fanCount: fanCount,
            'userInfo.followers': fanCount
          });
        } else {
          wx.showToast({ title: '获取粉丝数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('粉丝数量请求失败:', err);
        wx.showToast({ title: '粉丝数量加载失败', icon: 'none' });
      }
    });
  },

  // 加载收到的赞数量（已修复）
  loadLikesCount() {
    const { userId } = this.data; // 获取被查看用户的ID
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/likes/count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('收到的赞数量接口返回:', res.data);
        if (typeof res.data === 'number') { 
          const likesCount = res.data || 0;
          this.setData({
            likesCount: likesCount,
            'userInfo.likesReceived': likesCount
          });
        } else {
          wx.showToast({ title: '获取点赞数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('点赞数量请求失败:', err);
        wx.showToast({ title: '点赞数量加载失败', icon: 'none' });
      }
    });
  },

  // 菜谱点击跳转
  onRecipeTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/my/pages/recipe-detail/recipe-detail?id=${id}` });
  },

  // 作品点击跳转
  onWorkTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/my/pages/work-detail/work-detail?id=${id}` });
  },

  // 跳转关注列表
  gotoFollowed() {
    const { userId } = this.data;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/index/pages/followed/followed?userId=${userId}`,
    }).then(() => {
      // 返回后刷新关注数量
      setTimeout(() => this.loadFollowCount(), 500);
    });
  },

  // 跳转粉丝列表
  gotoFans() {
    const { userId } = this.data;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/index/pages/fans/fans?userId=${userId}`,
    }).then(() => {
      // 返回后刷新粉丝数量
      setTimeout(() => this.loadFanCount(), 500);
    });
  },

  // 跳转收到的赞列表
  gotoLikes() {
    const { userId } = this.data;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/my/pages/likes/likes?userId=${userId}`,
    }).then(() => {
      // 返回后刷新点赞数量
      setTimeout(() => this.loadLikesCount(), 500);
    });
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 分享功能
  onShareTap() {
    wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage', 'shareTimeline'] });
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: `${this.data.userInfo.name}的个人主页`,
      path: `/my/pages/user-detail/user-detail?id=${this.data.userId}`,
      imageUrl: this.data.userInfo.avatar
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return { title: `${this.data.userInfo.name}的个人主页` };
  }
});